package com.itheima.controller;

import com.itheima.annotation.LimitOperate;
import com.itheima.annotation.Syslog;
import com.itheima.common.Result;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理Controller
 */
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpService empService;
    /**
     * List result.
     *
     * @return the result
     */
    @GetMapping
//    @Syslog
    public Result<List<Dept>> list() {
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);

    }

    /**
     * Delete by id result.
     *
     * @param id the id
     * @return the result
     */
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    @LimitOperate
    public Result<?> deleteById(@PathVariable Integer id) {
        deptService.deleteById(id);
        // 根据部门id删除员工信息
//        System.out.println(1/0);
//        if (true) {
//            throw new Exception("异常");
//        }

        empService.deleteByDeptId(id);
//        System.out.println(1/0);
        return Result.success();
    }

    /**
     * Save result.
     *
     * @param dept the dept
     * @return the result
     */
    @PostMapping
    @LimitOperate
    public Result<?> save(@RequestBody Dept dept) {
        deptService.save(dept);
        return Result.success();
    }

    /**
     * Select dept by id result.
     *
     * @param id the id
     * @return the result
     */
    @GetMapping("/{id}")
    public Result<Dept> selectDeptById(@PathVariable Integer id) {
        Dept dept = deptService.selectDeptById(id);
        return Result.success(dept);
    }

    /**
     * Update dept result.
     *
     * @param dept the dept
     * @return the result
     */
    @PutMapping
    @LimitOperate
    public Result<?> updateDept(@RequestBody Dept dept) {
        deptService.updateDept(dept);
        return Result.success();
    }


}
